"""
    Author:
    Date: 2019-01-15

    微信管理后台-用户管理页面
"""

import datetime
import json
import time

from django.shortcuts import render

from entities import call_mgr
from entities import guild_mgr
from entities import photo_mgr
from entities import redis_mgr
from entities import room_mgr
from entities import server_mgr
from entities import user_mgr
from entities import video_mgr
from entities.consts import *
from utils import util
from utils import ajax

from .. import helpers
from .. helpers import gma_login_required


@gma_login_required
def index(request):
    """ 主播列表 """
    context = helpers.build_context(request)
    context['total_authing_caster_count'] = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_WAITING, request)
    context['total_rejected_caster_count'] = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_REJECTED, request)
    context['total_agreed_caster_count'] = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_CERTIFIED, request)

    # context['star5_caster_count'] = user_mgr.get_user_count_by_star(5, request)
    # context['star4_caster_count'] = user_mgr.get_user_count_by_star(4, request)
    # context['star3_caster_count'] = user_mgr.get_user_count_by_star(3, request)
    # context['star2_caster_count'] = user_mgr.get_user_count_by_star(2, request)
    # context['star1_caster_count'] = user_mgr.get_user_count_by_star(1, request)
    # context['star0_caster_count'] = user_mgr.get_user_count_by_star(0, request)

    return render(request, 'gma/caster/caster_home.html', context)


@gma_login_required
def detail(request, uid):
    """ 主播详情 """
    user = user_mgr.get_user_detail(uid)
    if user is None:
        return helpers.show_page_500(request, '该用户不存在!')

    # if not helpers.is_official_gm(request):
    #     gm_apps = helpers.get_request_gm_apps(request)
    #     if user['bundle_id'] not in gm_apps:
    #         return helpers.show_page_500(request, '权限不足!')

    is_caster = user_mgr.is_broadcaster(uid)
    is_authorised_caster = user_mgr.is_authorised_broadcaster(uid)
    guild_id = guild_mgr.get_user_guild_id(uid)

    context = helpers.build_context(request)
    context['user'] = user
    context['is_caster'] = is_caster
    context['is_authorised_caster'] = is_authorised_caster
    context['guild'] = guild_mgr.get_guild_info(guild_id) if guild_id else []
    context['is_banned'] = user_mgr.is_banned_user(uid)
    context['is_banned_device'] = user_mgr.is_banned_device(user['last_login_device'])
    context['is_banned_ip'] = user_mgr.is_banned_ip(user['last_login_ip'])

    context['total_call_seconds'] = user_mgr.get_broadcaster_total_call_seconds(uid)
    context['liveid'] = user_mgr.get_active_liveid(uid)
    context['is_ios_device'] = 'iphone' in user['last_login_phone'].lower()
    # 用户累计充值金额数
    context['total_pay_money_amount'] = user_mgr.get_user_total_paid_money_amount(uid)
    # 用户累计充值钻石数
    context['total_diamond_pay_amount'] = user_mgr.get_user_total_paid_diamond_amount(uid)
    # 用户累计输入钻石数
    context['total_diamond_input_amount'] = user_mgr.get_user_total_diamond_input_amount(uid)
    # 用户累计消费钻石数
    context['total_diamond_output_amount'] = user_mgr.get_user_total_diamond_output_amount(uid)

    context['is_busy'] = 'checked="checked"' if user['is_busy'] else ''
    context['is_ios_device'] = 'iphone' in user['last_login_phone'].lower()

    if is_caster:
        # 提取用户的相册
        sample_images = []
        if 'images' in user:
            sample_images = user['images'][:3] if user['images'] else []
        context['sample_images'] = sample_images
        context['auth_photo'] = photo_mgr.get_user_authing_photo_by(uid)

        context['total_online_seconds'] = user_mgr.get_broadcaster_total_online_seconds(uid)
        context['total_income'] = user_mgr.get_broadcaster_total_income(uid)
        context['total_video_count'] = video_mgr.get_user_video_count(uid)

        # 推荐位
        context['recommend_desp'] = user_mgr.get_user_recommend_desp(uid)

        context['is_recommended'] = 'checked="checked"' if user['is_recommended'] else ''

    context['room_tags'] = room_mgr.get_room_tag_list()

    return render(request, 'gma/caster/broadcaster_detail.html', context)


@gma_login_required
def search(request):
    """ 查找用户 """
    search_value = request.GET.get('search_value', '')
    if search_value == '':
        context = helpers.build_context(request)
        context['broadcasters'] = []
        context['total_count'] = 0
        return render(request, 'gma/caster/search_caster.html', context)

    search_value = search_value.strip()
    return search_by(request, search_value)


@gma_login_required
def search_by(request, search_value):
    """ 查找用户 """
    # 保存查询记录
    openid = helpers.get_request_openid(request)
    redis_mgr.cache_search_value(openid, search_value)

    if search_value.isdigit():
        digit = int(search_value)
        if user_mgr.is_valid_uid(digit):
            uid = digit
            return detail(request, uid)

        uid = user_mgr.get_uid_from_mobile(digit)
        if uid is not None:
            return detail(request, uid)

    users = user_mgr.search_user(search_value, 20, request)

    context = helpers.build_context(request)
    context['broadcasters'] = users
    context['total_count'] = len(users)
    return render(request, 'gma/caster/search_caster.html', context)


@gma_login_required
def online_stat(request, uid):
    """ 主播在线时长统计 """
    stat_data = []

    # 统计今天的在线时长
    today = datetime.date.today()
    batch = '%4d-%02d-%02d' % (today.year, today.month, today.day)
    today_online_seconds = user_mgr.get_broadcaster_today_online_seconds(uid)
    stat_data.append((batch, today_online_seconds))

    # 统计近期的在线时长数据
    begin = today
    for i in range(40):
        end = begin
        begin = begin - datetime.timedelta(days=1)
        batch = '%4d-%02d-%02d' % (begin.year, begin.month, begin.day)
        seconds = user_mgr.get_broadcaster_online_seconds(uid, util.datetimetostr(begin), util.datetimetostr(end))
        stat_data.append((batch, seconds))

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['stat_data'] = stat_data
    context['total_online_seconds'] = user_mgr.get_broadcaster_total_online_seconds(uid)
    return render(request, 'gma/caster/caster_online_stat.html', context)


@gma_login_required
def call_stat(request, uid):
    """ 主播通话时长统计 """
    # if user_mgr.is_broadcaster(uid):
    #     user = user_mgr.get_broadcaster_detail(uid)
    # else:
    #     user = user_mgr.get_user_detail(uid)
    #     user['uid'] = user['id']

    stat_data = []
    begin = datetime.date.today() + datetime.timedelta(days=1)
    for i in range(40):
        end = begin
        begin = begin - datetime.timedelta(days=1)
        batch = '%4d-%02d-%02d' % (begin.year, begin.month, begin.day)
        seconds = user_mgr.get_broadcaster_call_seconds(uid, util.datetimetostr(begin), util.datetimetostr(end))
        if seconds > 0:
            stat_data.append((batch, seconds))

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['stat_data'] = stat_data
    context['total_call_seconds'] = user_mgr.get_broadcaster_total_call_seconds(uid)
    return render(request, 'gma/caster/caster_call_stat.html', context)


@gma_login_required
def income_stat(request, uid):
    """ 主播收益统计 """
    stat_data = []
    begin = datetime.date.today() + datetime.timedelta(days=1)
    for i in range(15):
        end = begin
        begin = begin - datetime.timedelta(days=1)
        batch = '%4d-%02d-%02d' % (begin.year, begin.month, begin.day)
        income = user_mgr.get_broadcaster_income(uid, util.datetimetostr(begin), util.datetimetostr(end))
        if income > 0:
            stat_data.append((batch, income))

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['stat_data'] = stat_data
    context['total_income'] = user_mgr.get_broadcaster_total_income(uid)
    return render(request, 'gma/caster/caster_income_stat.html', context)


@gma_login_required
def recommend_caster_list(request):
    """ 推荐的主播列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_broadcaster_list(250, request=request)
    context['total_count'] = user_mgr.get_recommend_user_count(request=request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def authing_caster_list(request):
    """ 等待审核的主播列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_auth_user_list_by_status(AUTH_STATUS_WAITING, 20, request)
    context['total_count'] = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_WAITING, request)
    return render(request, 'gma/caster/caster_list_auth.html', context)


@gma_login_required
def rejected_caster_list(request):
    """ 审核被拒的主播列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_auth_user_list_by_status(AUTH_STATUS_REJECTED, 20, request)
    context['total_count'] = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_REJECTED, request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def agreed_caster_list(request):
    """ 审核通过的主播列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_auth_user_list_by_status(AUTH_STATUS_CERTIFIED, 20, request)
    context['total_count'] = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_CERTIFIED, request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def banned_caster_list(request):
    """ 被封禁的用户列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_banned_user_list(request=request)
    context['total_count'] = user_mgr.get_banned_user_count(request=request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def casters_by_star(request, star):
    """ 分星级的用户列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_user_list_by_star(star, 500, request)
    context['total_count'] = user_mgr.get_user_count_by_star(star, request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def watcher_list(request):
    """ 用户列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_watcher_list(250, request=request)
    context['total_count'] = user_mgr.get_total_watcher_count(request=request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def vip_list(request):
    """ vip用户列表 """
    casters = user_mgr.get_vip_list(50, request=request)
    for caster in casters:
        card_type = caster['card_type']
        caster['vip_card_desp'] = get_vip_card_desp(card_type)
        caster['is_expired'] = util.datetimetotime(caster['buy_vip_card_time']) + get_vip_card_time(card_type) < time.time()
    casters.sort(key=lambda x: x['is_expired'])

    context = helpers.build_context(request)
    context['casters'] = casters
    context['total_count'] = user_mgr.get_total_vip_count(request=request)
    return render(request, 'gma/caster/vip_list.html', context)


@gma_login_required
def online_detail(request, uid, begin, end):
    """ 获取用户的在线详细数据 """
    if begin == end:
        end = end + ' 23:59:59'

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['logs'] = user_mgr.get_broadcaster_online_records(uid, begin, end)
    context['total_online_seconds'] = user_mgr.get_broadcaster_online_seconds(uid, begin, end)
    return render(request, 'gma/caster/caster_online_detail.html', context)


@gma_login_required
def call_detail(request, uid, begin, end):
    """ 获取用户的通话详细数据 """
    if begin == end:
        end = end + ' 23:59:59'

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['begin_time'] = begin
    context['end_time'] = end
    context['logs'] = user_mgr.get_broadcaster_call_records(uid, begin, end)
    context['total_call_seconds'] = user_mgr.get_broadcaster_call_seconds(uid, begin, end)
    return render(request, 'gma/caster/caster_call_detail.html', context)


@gma_login_required
def video_chat_log(request, call_id, caller_uid, callee_uid):
    """ 获取视频通话记录 """
    log   = call_mgr.get_broadcaster_call_record(call_id)
    if log['chatlog_url'] == '' and log['record_sid'] != '':
        sid = log['record_sid']
        liveid = log['id']
        log['chatlog_url'] = f'http://chatlog.mqnetswork.com/{sid}_{liveid}.m3u8'

    terminator_uid = log['terminator_uid']
    log['terminator_is_caster'] = True if terminator_uid > 0 and user_mgr.is_broadcaster(terminator_uid) else False

    context = helpers.build_context(request)
    context['caller'] = user_mgr.get_user_detail(caller_uid)
    context['callee'] = user_mgr.get_user_detail(callee_uid)
    context['log'] = log
    return render(request, 'gma/caster/video_chat_log.html', context)


@gma_login_required
def video_list(request, uid):
    """ 获取用户的视频列表 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['videos'] = video_mgr.get_user_video_list(uid)
    return render(request, 'gma/caster/caster_video_list.html', context)


@gma_login_required
def user_login_data(request, uid):
    """ 获取用户的登录数据 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/user_login_data.html', context)


@gma_login_required
def user_login_detail_list(request, uid):
    """ 获取用户的登录详情 """
    user = user_mgr.get_user_detail(uid)
    # 显示从用户创建日期开始的所有日期
    days = util.get_last_days_info(30)
    days = [x for x in days if (x[0] >= util.datetimetostr(user['create_time'])[:10]) and (x[0] <= util.datetimetostr(user['last_login_time'])[:10])]

    context = helpers.build_context(request)
    context['user'] = user
    context['days'] = days
    return render(request, 'gma/caster/user_login_detail_list.html', context)


@gma_login_required
def user_login_detail(request, uid, day):
    """ 用户指定日期的登录详情 """
    user = user_mgr.get_user_detail(uid)
    context = helpers.build_context(request)
    context['user'] = user
    context['day'] = day
    context['logs'] = server_mgr.get_user_action_logs(uid, day, user['mobile'], user['openid'])
    return render(request, 'gma/caster/user_login_detail.html', context)


@gma_login_required
def user_raw_data(request, uid):
    """ 获取用户的RAW数据 """

    # 将用户数据排序
    user = user_mgr.get_user_detail(uid)
    sorted_user_data = []
    for k in user:
        if k in ['index_', 'token', 'avatar']:
            continue
        v = user[k]
        if k.endswith('_time'):
            v = util.datetimetostr(v)
        sorted_user_data.append((k, v))
    sorted_user_data.sort()

    # 将用户数据排序
    auth = user_mgr.get_user_auth_detail(uid)
    auth = auth if auth else {}
    sorted_auth_data = []
    for k in auth:
        if k in ['index_']:
            continue
        v = auth[k]
        if k.endswith('_time'):
            v = util.datetimetostr(v)
        t = 'div'
        if 'json' in k:
            t = 'textarea'
        sorted_auth_data.append((k, v, t))
    sorted_auth_data.sort()

    context = helpers.build_context(request)
    context['user'] = user
    context['user_raw_data'] = sorted_user_data
    context['auth_raw_data'] = sorted_auth_data
    return render(request, 'gma/caster/user_raw_data.html', context)


@gma_login_required
def user_personal_data(request, uid):
    """ 用户的个人资料 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/user_personal_data.html', context)


@gma_login_required
def user_album(request, uid):
    """ 个人相册 """
    auth_images = []
    photo = photo_mgr.get_user_authing_photo_by(uid)

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['auth_images'] = auth_images
    context['photo'] = photo
    return render(request, 'gma/caster/user_album.html', context)


@gma_login_required
def user_hx_message(request, uid):
    """ 给用户发送私信的页面 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/send_hx_message.html', context)


@gma_login_required
def user_pay_detail(request, uid):
    """ 用户充值详情 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['total_paid_amount'] = user_mgr.get_user_total_paid_amount(uid)
    context['data'] = user_mgr.get_user_recharge_list(uid, 1000)
    return render(request, 'gma/caster/user_pay_list.html', context)


@gma_login_required
def user_diamond_input_detail(request, uid):
    """ 用户钻石获得详情 """
    data = user_mgr.get_user_diamond_input_records(uid, 1000)
    for record in data:
        record['type_desp'] = get_consumption_type_desp(record['type'])

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['data'] = data
    # 用户累计输入钻石数
    context['total_diamond_input_amount'] = user_mgr.get_user_total_diamond_input_amount(uid)
    return render(request, 'gma/caster/user_diamond_input_list.html', context)


@gma_login_required
def user_diamond_output_detail(request, uid):
    """ 用户钻石消耗详情 """
    data = user_mgr.get_user_diamond_output_records(uid, 1000)
    for record in data:
        record['type_desp'] = get_consumption_type_desp(record['type'])

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['data'] = data
    # 用户累计消费钻石数
    context['total_diamond_output_amount'] = user_mgr.get_user_total_diamond_output_amount(uid)
    return render(request, 'gma/caster/user_diamond_output_list.html', context)


@gma_login_required
def user_ticket_input_detail(request, uid, begin, end):
    """ 用户趣票收益详情 """
    if begin == end and len(begin) == len('2019-01-01'):
        end = end + ' 23:59:59'

    data = user_mgr.get_user_ticket_input_records(uid, begin, end)
    for record in data:
        record['type_desp'] = get_consumption_type_desp(record['type'])

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['data'] = data
    context['total_ticket_input_amount'] = user_mgr.get_broadcaster_income(uid, begin, end)
    return render(request, 'gma/caster/user_ticket_input_list.html', context)


@gma_login_required
def my_invited_user_list(request, aid):
    """ 邀请的用户列表 """
    aid = int(aid)

    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_agent_invited_user_list(aid, 50)
    context['total_count'] = user_mgr.get_agent_invited_user_count(aid)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def caster_recommend_page(request, uid):
    """ 调整主播的推荐位页面 """
    user = user_mgr.get_user_detail(uid)
    if user is None:
        return helpers.show_page_500(request, '该用户不存在!')

    context = helpers.build_context(request)
    context['user'] = user
    context['max_recommend_value'] = user_mgr.get_max_recommend_value()
    context['min_recommend_value'] = user_mgr.get_min_recommend_value()
    context['recommend_position'] = user_mgr.get_recommend_position(uid)
    context['recommend_desp'] = user_mgr.get_user_recommend_desp(uid)
    return render(request, 'gma/caster/caster_recommend.html', context)


@gma_login_required
def free_chat_caster_list(request):
    """ 开通免费通话功能的主播列表 """
    context = helpers.build_context(request)
    context['casters'] = user_mgr.get_free_chat_caster_list(250, request=request)
    context['total_count'] = user_mgr.get_allow_free_chat_caster_count(request=request)
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def modify_caster_nickname(request, uid):
    """ 修改主播昵称页面 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/modify_caster_nickname.html', context)


@gma_login_required
def modify_caster_signature(request, uid):
    """ 修改主播签名页面 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/modify_caster_signature.html', context)


@gma_login_required
def modify_caster_introduction(request, uid):
    """ 修改主播介绍页面 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/modify_caster_introduction.html', context)


@gma_login_required
def edit_room_heat_factor(request, uid):
    """ 编辑房间热度系数 """
    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    return render(request, 'gma/caster/edit_room_heat_factor.html', context)


@gma_login_required
def api_edit_room_extra_heat(request):
    """ 编辑房间的附加热度 """
    uid = int(request.POST['uid'].strip())
    extra_heat = int(request.POST.get('extra_heat', '0').strip())

    if extra_heat < 0:
        return ajax.error_response('无效的热度值!')

    if extra_heat > 50000:
        return ajax.error_response('附加热度值过高!')

    ok = user_mgr.update_room_extra_heat(uid, extra_heat)
    if not ok:
        return ajax.error_response('修改失败!')
    return ajax.success_response(None, '修改成功!')


if __name__ == '__main__':
    print('ok')
